<?php

namespace App\Http\Controllers\Admin;

use App\Admin\Form;
use App\Admin\Layout\Content;
use App\Admin\Traits\ModelForm;
use App\Admin\Tree;
use App\Http\Controllers\Controller;
use App\Models\Menu;

class MenuController extends Controller
{
    use ModelForm;

    public function index()
    {
        return \Admin::content(function (Content $content) {
            $content->header('菜单');
            $content->description('菜单列表');

            $content->body($this->treeView()->render());
        });
    }

    public function create()
    {
        return \Admin::content(function (Content $content) {
            $content->header('菜单');
            $content->description('添加新菜单');
            $content->row($this->form());
        });
    }

    public function edit($id)
    {
        return \Admin::content(function (Content $content) use ($id) {
            $content->header('菜单');
            $content->description('编辑菜单');

            $content->row($this->form()->edit($id));
        });
    }

    public function form()
    {
        return Menu::form(function (Form $form) {
            $form->display('id', '编号');

            $form->select('parent_id', '父级菜单')->options(Menu::selectOptions());
            $form->text('title', '菜单名称');
            $form->icon('icon', '菜单图标')->default('fa-cogs');
            $form->text('uri', '菜单地址')->prepend('/admin/');

            $form->display('created_at', '添加时间');
            $form->display('updated_at', '修改时间');
        });
    }

    protected function treeView()
    {
        return Menu::tree(function (Tree $tree) {
            $tree->branch(function ($branch) {
                $icon_html = fa_icon($branch['icon']);
                $payload = "{$icon_html}&nbsp;{$branch['title']}";

                if (!isset($branch['children'])) {
                    $uri = \Admin::url($branch['uri']);

                    $payload .= "&nbsp;&nbsp;&nbsp;<a class='grid-link dd-nodrag' href=\"{$uri}\" class=\"dd-nodrag\">{$uri}</a>";
                }

                return $payload;
            });

            $tree->nestable([
                'maxDepth' => 99,
            ]);
        });
    }
}
